<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <div class="title">规则设置</div>
      <!-- 兜底规则提示语 -->
      <div>
        <div class="warning">
          <img src="https://img.bzhz.jnbygroup.com/dincanwarn.png" alt="">
          <div>{{Warningtext3}}</div>
        </div>
        <a-tabs type="card" @change="topcallback" style="margin:20px 0 0 20px;" :defaultActiveKey="activeDefaulttype" >
          <a-tab-pane key="1" tab="门店码">
          </a-tab-pane>
          <a-tab-pane key="2" tab="导购码">
          </a-tab-pane>
          <a-tab-pane key="3" tab="企微导购码">
          </a-tab-pane>
        </a-tabs>
      </div>
      <div class="base">消息设置</div>
      <div style="display:flex;align-items:center;">
        <!-- 消息设置for循环的div -->
        <div style="margin-right:20px;">
          <div class="content" v-for="(item,i) in model.itemList" :key="item.id">
            <div style="position: relative;">
              <a-tabs type="card"  :defaultActiveKey="item.type + ''" @change="callback(i,$event)">
                <a-tab-pane key="1" tab="文字" :disabled='item.disabledtext'>
                </a-tab-pane>
                <a-tab-pane key="2" tab="图片" :disabled='item.disabledimg'>
                </a-tab-pane>
                <a-tab-pane key="3" tab="小程序卡片" :disabled='item.disabledcard'>
                </a-tab-pane>
              </a-tabs>
              <div class="jt">
                <img src="https://img.bzhz.jnbygroup.com/dincanup.png" alt="" style="margin-right:15px;" @click="up(i)">
                <img src="https://img.bzhz.jnbygroup.com/dincandown.png" alt="" @click="down(i)">
              </div>
            </div>
            <div v-if="item.type == 1">
              <div class="container" ref="wise" style="position: relative;">
                <atextarea
                  v-model="item.content"
                  :tag="tag"
                  ref="testText"
                  maxlength="200"
                  @add="handleAdd"
                  :itemIndex='i'
                  @message="message"
              >
              </atextarea>
              </div>
            </div>
            <div class="" v-if="item.type == 2">
              <JImageUpload 
                :uploadParams="getUploadParams1()" 
                :isMultiple="false" 
                :accept="'image/*'"
                :fileSize="1" 
                @fileChange="fileImageChange(i,$event)" 
                v-model="item.imageUrl"
              ></JImageUpload>
              <div class="tips">仅支持PNG\JPG\JPEG\GIF格式，文件大小不超过1M</div>
            </div>
            <div class="" v-show="item.type == 3">
              <a-form-model ref="form" :model="item.miniProgramDto" >
                <a-form-model-item
                  prop="appId"
                  label="小程序APP ID">
                  <a-tooltip>
                    <template slot="title">
                      <div>本字段为非必填项</div>
                      <div>如填写则以填写为准进行跳转</div>
                      <div>如不填写则取对应导购/公众号的品牌对应跳转</div>
                    </template>
                    <img src="./tip.png" alt="" style="width:13px;height:13px;position: absolute;top: -39px;left: 99px;" >
                  </a-tooltip>
                  <a-input placeholder="非必填项,不填写则取对应品牌跳转" style="width:325px;" :maxLength="50" v-model="item.miniProgramDto.appId"/>
                </a-form-model-item>

                <a-form-model-item
                prop=""
                label="路径">
                <a-select default-value="lucy" style="width: 325px" v-model="item.miniProgramDto.type" @change="urlhandleChange(item,i)" placeholder="请选择">
                  <a-select-option :value="aitem.value" v-for="aitem in optionUrl" :key="aitem.value">
                    {{aitem.name}}
                  </a-select-option>
                </a-select>
              </a-form-model-item>

                <a-form-model-item
                  prop="url"
                  label="">
                  <a-input placeholder="请填写路径" style="width:325px;"  :maxLength="200" v-model="item.miniProgramDto.url" v-show="item.miniProgramDto.type == 1" />
                </a-form-model-item>

                <a-form-model-item
                  prop="title"
                  label="标题">
                  <a-input placeholder="最多支持25个字" style="width:325px;"  :maxLength="25" v-model="item.miniProgramDto.title"/>
                </a-form-model-item>

                <a-form-model-item
                  prop="image"
                  label="图片">
                  <JImageUpload 
                    :uploadParams="getUploadParams()" 
                    :isMultiple="false" 
                    :accept="'image/*'"
                    :fileSize="1" 
                    @fileChange="kpfileChange(i,$event)" 
                    v-model="item.miniProgramDto.image"
                  ></JImageUpload>
                  <div class="tips">尺寸为520*416，仅支持PNG\JPG\JPEG\GIF格式，文件大小不超过500K</div>
                </a-form-model-item>
              </a-form-model>
            </div>
            <div class="save">
              <a-button type="" style="margin-right:10px;" @click="delmessage(i)">删除消息</a-button>
              <a-button type="primary" @click="saveMessage(item,i)">保存消息</a-button>
            </div>
          </div>
        </div>
        <!-- 表情插件 -->
        <div style="position: relative;">
          <div v-show="showPicker" style="width:500px;">
            <emoji-picker
              v-model="value888"
              button
              style="background: #ddd"
              height="300px"
            />
            <div>
              <input v-model="value888" style="width: 400px;height: 40px;border: 1px solid #EFEFEF;margin-top: 20px;" />
              <button @click="send" style="height: 40px;width: 100px;border: none; ">确定</button> 
            </div>
          </div>
        </div>
      </div>
      <div class="add">
        <div>
          <a-button @click="addmessage">添加消息</a-button>
        </div>
        <div style="margin-top:5px;">最多支持添加3条消息</div>
      </div>
      <div style="text-align:center;margin-top:70px;">
        <a-button @click="cencal"> 取消 </a-button>
        <a-button type="primary" @click="save" style="margin-left: 10px">保存</a-button>
      </div>
    </div>

    <a-modal v-model="linkvisible" title="" @ok="addTag" ok-text="插入" @cancel="cancel">
      <!-- <a-form-model ref="form" :model="hyperlinkDto" v-show="linktype == 1">
        <a-form-model-item
          prop="text"
          label="文本内容">
          <a-input placeholder="请输入" style="width:325px;" v-model="hyperlinkDto.text"/>
        </a-form-model-item>
        <a-form-model-item
          prop="url"
          label="链接地址">
          <a-input placeholder="请输入" style="width:325px;"  v-model="hyperlinkDto.url"/>
        </a-form-model-item>
      </a-form-model>
      <a-form-model ref="form" :model="miniProgramLinkDto" v-show="linktype == 2">
        <a-form-model-item
          prop="text"
          label="文本内容">
          <a-input placeholder="请输入" style="width:325px;" v-model="miniProgramLinkDto.text"/>
        </a-form-model-item>
        <a-form-model-item
          prop="appId"
          label="小程序APP ID">
          <a-input placeholder="请输入" style="width:325px;"  v-model="miniProgramLinkDto.appId"/>
        </a-form-model-item>
        <a-form-model-item
          prop="url"
          label="路径">
          <a-input placeholder="请输入" style="width:325px;"  v-model="miniProgramLinkDto.url"/>
        </a-form-model-item>
      </a-form-model> -->
      
      <div style="margin-top:20px;" v-show="linktype == 4">
        <a-button 
          class="blbtn" 
          @click="blclick(item.name)" 
          v-for="(item,index) of blnameList" 
          :key="index"
        >
          {{item.name}}
        </a-button>
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import { saveOrUpdateWelcome, DefaultWelcomeVo  } from '@/api/marketingCenter/code'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import globalData from '@/assets/js/common'
import atextarea from './textarea'
import '../vue-weixin-emojis.css'

export default {
  components: {
    JImageUpload,
    atextarea,
  },
  name:'xx',
  data() {
    return {
      value888:'',
      activeDefaulttype:'1', //兜底规则tab切换
      showPicker: false, // 控制显示隐藏表情插件
      itemi:'',
      linkvisible:false,
      linktype:'',
      // 超链接对象
      hyperlinkDto:{}, 
      // 小程序超链接对象
      miniProgramLinkDto:{},
      Warningtext3:'设置兜底规则后，所有未设置规则的门店码、导购码和企微导购码将默认走兜底规则。当设置对应规则后以新设置的规则为准，兜底逻辑不再生效。如果设置了规则但被禁用，也将走兜底逻辑',
      // 指定变量
      blname:'',
      blnameList:[
        {
          name:'对应品牌'
        },
        {
          name:'对应集团卡等级'
        },
        {
          name:'对应品牌卡等级'
        },
        {
          name:'对应卡号'
        },
        {
          name:'导购店铺'
        },
        {
          name:'对应导购'
        },
      ],
      model: {
        itemList:[
          {
            content:'',
            imageUrl:'',
            type:1,
            hyperlinkDto:{},
            miniProgramLinkDto:{
              url:'',
              title:'',
              appId:'',
            },
            miniProgramDto:{},
            disabledtext:false,
            disabledimg:false,
            disabledcard:false,
          }
        ]
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      ruleoption:[
        {
          value:1,
          name:'门店码(公众号)'
        },
        {
          value:2,
          name:'导购码(公众号)'
        },
        {
          value:3,
          name:'企微导购码(公众号)'
        },
      ],
      // 校验
      validatorRules: {
        name: [{ required: true, message: '请输入' }],
        type: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
      optionUrl:[
        {
          value:1,
          name:'自定义路径',
        },
        {
          value:2,
          name:'开卡链接',
        },
      ],
      tag:'a'
    }
  },
  created() {
    this.getDefaultWelcomeVo()
  },
  methods:{
    //页面取消
    cencal() {
      this.$router.push(`/marketingCenter/code/welcomewords`)
    },
    // 兜底规则list
    getDefaultWelcomeVo() {
      DefaultWelcomeVo({type:this.activeDefaulttype}).then(res => {
        console.log(res.data.itemList);
        if (res.code == 200 && res.data.itemList !== undefined) {
          res.data.itemList.forEach(el => {
            var regex2 = /\[(.+?)\]/g;
            let a1 = el.content.replace(regex2,(ccc) => {
              return `<wise>${ccc}</wise>`
            })
            el.content = this.$string2emoji(a1)
            if (el.type == 1) {
              el.disabledimg = true
              el.disabledcard = true
            } else if (el.type == 2) {
              el.disabledtext = true
              el.disabledcard = true
            } else if (el.type == 3) {
              el.disabledtext = true
              el.disabledimg = true
            }
          })
          this.model = res.data
        } else if (res.code == 200 && res.data.itemList == undefined) {
            this.model = {
              id:'',
              itemList:[]
            }
          }
      })
    },
    // 顶部tab切换
    topcallback(e) {
      this.activeDefaulttype = e
      this.getDefaultWelcomeVo()
      this.model.itemList = [
        {
          content:'',
          imageUrl:'',
          type:1,
          hyperlinkDto:{},
          miniProgramLinkDto:{},
          miniProgramDto:{},
          disabledtext:false,
          disabledimg:false,
          disabledcard:false,
        }
      ]
    },
    // 消息设置里的tab切换
    callback(i,e) {
      this.showPicker = false
      this.model.itemList[i].type = e
    },
    blclick(name) {
      this.blname = name
    },
    addmessage() {
      this.showPicker = false
      if (this.model.itemList !== undefined && this.model.itemList.length >= 3) return
      let typeNum = 1
      let typeList =  this.model.itemList.map(el => {
        return el.type
      })
      if (!typeList.includes(2)) {
        typeNum = 2
      } else if (!typeList.includes(3)) {
        typeNum = 3
      }
      this.model.itemList.push(
        {
          content:'',
          imageUrl:'',
          type:typeNum,
          hyperlinkDto:{},
          miniProgramLinkDto:{},
          miniProgramDto:{},
          disabledtext:false,
          disabledimg:false,
          disabledcard:false,
        }
      )
    },
    cancel() {
      this.hyperlinkDto = {}
      this.miniProgramLinkDto = {}
    },
    up(index){
      let item =  this.model.itemList[index]
      this.model.itemList.splice(index,1)
      this.model.itemList.splice(index-1,0,item)
    },
    down(index){
      let item = this.model.itemList[index]
      this.model.itemList.splice(index,1)
      this.model.itemList.splice(index+1,0,item)
    },  
    // 图片编辑
    fileImageChange(i,list) {
      if (list.length == 0) {
        this.model.itemList[i].imageUrl = ''
      }
      if (list.length == 0 ||list[0].response == undefined) return
      this.model.itemList[i].imageUrl = list[0].response.data 
    },
    // 上传图片
    getUploadParams() {
      return { ...globalData.uploadParams }
    },
    // 小程序卡片上传图片
    getUploadParams1() {
      // return {
      //   actionUrl: '/a/backend/qrcode/uploadCpImage',
      // }
      let baseUrl = window._CONFIG['domianURL'] || "/jeecg-boot"
      return {
        actionUrl: baseUrl + '/api/gateway/jic-backend-activity/' + '/backend/qrcode/uploadCpImage',
      }
    },
    // 小程序卡片图片编辑
    kpfileChange(i,list) {
      this.model.itemList[i].miniProgramDto.image = list.length ? list[0].url : ''
    },
    saveMessage(item,i) {
      this.showPicker = false
      if (item.type == 1) {
        if (item.content == '' || item.content == undefined) {
          return this.$message.warning('请提供内容后再保存消息');
        } else {
          this.disableType(item)
          this.$message.success('保存消息成功')
        }
      } else if (item.type == 2) {
        if (item.imageUrl == '' || item.imageUrl == undefined) {
          return this.$message.warning('请提供内容后再保存消息');
        } else {
          this.disableType(item)
          this.$message.success('保存消息成功')
        }
      } else if (item.type == 3 && item.miniProgramDto.type == 2) {
        if ( item.miniProgramDto.title == '' || item.miniProgramDto.title == undefined ||  item.miniProgramDto.image == '' ||item.miniProgramDto.image == undefined ) {
          return this.$message.warning('请提供内容后再保存消息');
        } else {
          this.disableType(item)
          this.$message.success('保存消息成功')
        }
      } else if (item.type == 3 && item.miniProgramDto.type == 1) {
        if ( item.miniProgramDto.title == '' || item.miniProgramDto.image == '' ||  item.miniProgramDto.url == '' || item.miniProgramDto.title == undefined || item.miniProgramDto.image == undefined ||  item.miniProgramDto.url == undefined) {
          return this.$message.warning('请提供内容后再保存消息');
        } else {
          this.disableType(item)
          this.$message.success('保存消息成功')
        }
      } else {
        return this.$message.warning('请提供内容后再保存消息');
      }
    },
    disableType(item) {
      if (item.type == 1) {
        this.$set(item,'disabledimg',true)
        this.$set(item,'disabledcard',true)
      } else if (item.type == 2) {
        this.$set(item,'disabledtext',true)
        this.$set(item,'disabledcard',true)
      } else if (item.type == 3) {
        this.$set(item,'disabledtext',true)
        this.$set(item,'disabledimg',true)
      }
    },
    delmessage(index) {
      // if (this.model.itemList.length == 1) return
      this.showPicker = false
      this.model.itemList.splice(index,1)
    },
    addEmoji(e) {
      this.$refs.testText[this.itemi].addEmoji(e)
      this.showPicker = false
    },
    save() {
      this.showPicker = false
      let data = this.model
      if (data.itemList.length == 0) {
        return this.$message.warning('请提供内容后再保存消息')
      }
      let opennext = true // 循环结束，调用接口
      data.itemList.forEach(el => {
        // 取消了小程序appid校验
        if (el.type == 1) {
          if (el.content == '' || el.content == undefined) {
              opennext = false
              return this.$message.warning('请提供内容后再保存消息');
            }
        } else if (el.type == 2) {
          if (el.imageUrl == '' || el.imageUrl == undefined) {
            opennext = false
              return this.$message.warning('请提供内容后再保存消息');
          } 
        } else if (el.type == 3 && el.miniProgramDto.type == 2) {
          if ( el.miniProgramDto.title == '' || el.miniProgramDto.title == undefined ||  el.miniProgramDto.image == '' ||el.miniProgramDto.image == undefined ) {
            opennext = false
            return this.$message.warning('请提供内容后再保存消息');
          } 
        } else if (el.type == 3 && el.miniProgramDto.type == 1) {
          if ( el.miniProgramDto.title == '' || el.miniProgramDto.image == '' ||  el.miniProgramDto.url == '' || el.miniProgramDto.title == undefined || el.miniProgramDto.image == undefined ||  el.miniProgramDto.url == undefined) {
            opennext = false
            return this.$message.warning('请提供内容后再保存消息');
          }
        } else {
          opennext = false
          return this.$message.warning('请提供内容后再保存消息');
        }
      })
      if (opennext) {
        // 插入表情正则转码=
        data.itemList.forEach(el => {
          if (el.type == 1) {
            var str = el.content;
            let reg = new RegExp(`<wise(?:(?!<\/wise>).|\n)*?<\/wise>`,'gm')
            let aaa = str.replace(/(<\/?wise.*?>)/g, '');
            el.content = this.$emoji2string(aaa)
          }
        })
        data.isDefault = 1
        data.type = this.activeDefaulttype
        saveOrUpdateWelcome(data).then(res => {
          if(res.code == 200) {
            this.$message.success(res.msg)
            this.$router.push('/marketingCenter/code/welcomewords')
          } else {
            this.$message.error(res.msg)
          }
        })
      }
    },
    message(e) {
      this.$message.error(e)
    },
    send() {
      let str = this.$string2emoji(this.value888)
      this.addEmoji(str)
      this.value888 = "";
    },
    // -----------------------------
    handleAdd(type,itemIndex) {
      console.log(type);
      this.itemi = itemIndex
      if (type == 3) {
        // type为3 选择表情插件显示
        this.showPicker = true
      } else {
        // 插入指定变量
        this.linkvisible = true;
        this.tag = 'a'
        this.linktype = type
      }
    },
    addTag() {
      let bl = ''
      // if (this.linktype == 1) {
      //   bl = this.hyperlinkDto.text
      //   this.$refs.testText[this.itemi].addLink(bl,this.hyperlinkDto.url);
      // } else if (this.linktype == 2) {
      //   bl = this.miniProgramLinkDto.text
      //    this.$refs.testText[this.itemi].addLink(bl,this.miniProgramLinkDto.url);
      // } else if (this.linktype == 4) {
      //   bl = this.blname
      // }
      bl = this.blname
      this.$refs.testText[this.itemi].addTag(bl);
      // this.$refs.testText[this.itemi].addLink(bl,'www.baidu.com');
      this.linkvisible = false;
      this.hyperlinkDto = {}
      this.miniProgramLinkDto = {}
    },
    urlhandleChange(item,i) {
      if (this.model.itemList[i].miniProgramDto.type == 2) {
        this.$set(this.model.itemList[i].miniProgramDto,'title','欢迎加入江南布衣大家庭')
        this.$set(this.model.itemList[i].miniProgramDto,'image','https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20211221/007dee0e5f08e5164f8a9937b2b3f570.png')
      } else if (this.model.itemList[i].miniProgramDto.type == 1) {
        this.$set(this.model.itemList[i].miniProgramDto,'url','')
        this.$set(this.model.itemList[i].miniProgramDto,'title','')
        this.$set(this.model.itemList[i].miniProgramDto,'image','')
      }
    },
  }
}
</script>

<style scoped  lang="less" >
.title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
}
.warning {
  background-color: #fffbe6;
  width: 700px;
  padding:20px 20px 20px 80px;
  margin-left: 20px;
  display: flex;
  img {
    width: 20px;
    height: 20px;
    margin-right:10px;
  }
}
.base {
  margin: 20px;
  font-size: 20px;
  font-weight: 600;
}
.content {
  background-color:#f0f2f5;
  padding: 20px 30px;
  margin-left: 20px;
  margin-bottom: 20px;
  width: 700px;
}
/deep/.ant-radio-group {
  line-height: 2.5 !important;
}
// input
.texbox {
  position: relative;
}
.limit {
  right: 17px;
  position: absolute;
  bottom: 0;
  margin-right: 5px;
}
.textarea-wrapper {
  position: relative;
  display: block;
  .m-textarea {
    padding: 8px 12px;
    height: 100%;
  }
  .m-count {
    color: #808080;
    background: #fff;
    position: absolute;
    font-size: 12px;
    bottom: 8px;
    right: 12px;
  }
}
.link {
  margin-right: 50px;
  text-decoration: underline;
}
.save {
  display: flex;
  justify-content: flex-end;
}
.jt {
    position: absolute;
    top: 8px;
    right: 0;
    display: flex;
  img {
    width:23px;
    height: 23px;
  }
}
.add {
  margin-top: 20px;
  width: 721px;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
.content .ant-form-item {
  margin-bottom: 0px !important;
}
.blbtn {
  width: 100%;
}
// ---------css取消插件文字
.emoji-mart[data-v-7bc71df8] {
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", sans-serif;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-direction: column;
  flex-direction: column;
  height: 420px;
  color: #ffffff !important;
  border: 1px solid #d9d9d9;
  border-radius: 5px;
  background: #fff;
}
</style>